<template>
  <div class="front serve">
    <div class="header-box">
      <Header></Header>
    </div>
    <div class="content address">
      <el-radio v-model="logicId" label="1">快递</el-radio>
      <el-radio v-model="logicId" label="0">门店自提</el-radio>
      <div v-if="logicId == 1" class="title">确认收货地址</div>
      <ul v-if="logicId == 1" class="list">
        <li class="item" :class="{'on': addressId == address.id}" v-for="address in addressList" :key="address.id">
          <img src="@/assets/address.png" alt="" class="icon">
          <div class="titl">寄送至</div>
          <el-radio v-model="addressId" :label="address.id" class="con">
            {{address.provinceName}}
            {{address.cityName}}
            {{address.districtName}}
            {{address.address}}
            ({{address.name}}收)
            {{address.mobile}}
          </el-radio>
          <div class="btn" @click="handleUpdate(address)">修改地址</div>
        </li>
      </ul>
      <div v-if="logicId == 1" class="add" @click="handleAdd">使用其他地址</div>
      <div class="order-infor">
        <div class="title">确认订单信息</div>
        <ul class="seller-infor">
          <li class="seller" v-for="seller in confirmInfor.countDTOS" :key="seller.gongyingId">
            <div class="seller-name">店铺：{{seller.gongyingName}}</div>
            <ul class="product-list">
              <li class="product" v-for="product in seller.detailList" :key="product.productId">
                <img :src="product.image" alt="" class="icon">
                <div class="name">{{product.name}}</div>
                <div class="specifications">规格：{{product.productSkuName}}</div>
                <div class="price">¥{{product.price}}元</div>
                <div class="num">{{product.num}}{{product.unit}}</div>
                <div class="total-price">¥{{product.priceCount}}元</div>
              </li>
            </ul>
            <div class="bottom-wrapper">
              <div class="left">
                <div class="titl">给卖家留言</div>
                <textarea class="msg" v-model="seller.remark"></textarea>
              </div>
              <div class="right">
                <!--                <div class="text">-->
                <!--                  <div class="titl">配送方式：</div>-->
                <!--                  <div class="con">快递免邮</div>-->
                <!--                </div>-->
                <div class="text">
                  <div class="titl">店铺合计：</div>
                  <div class="con c">¥<span class="m">{{seller.payAmount}}元</span></div>
                </div>
              </div>
            </div>
          </li>
        </ul>
        <div class="total">实付款 <span class="c">¥<span class="m">{{confirmInfor.payAmount}}元</span></span></div>
        <div class="buyer-wrapper" v-for="address in addressList" :key="address.id">
          <template v-if="addressId == address.id">
            <div class="infor">寄送至： {{address.provinceName}}
              {{address.cityName}}
              {{address.districtName}}
              {{address.address}}</div>
            <div class="infor">收货人：{{address.name}}
              {{address.mobile}}</div>
          </template>
        </div>
        <div class="submit-wrapper">
          <button type="button" class="submit" @click="handleCreate" :disabled="flag">提交订单</button>
          <!-- <div class="return" @click="$router.push('/cart')">返回购物车</div> -->
        </div>
      </div>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="88px"
        style="margin: 0 50px;">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="temp.mobile" />
        </el-form-item>
        <!-- <el-form-item label="编号">
          <el-input v-model="temp.identifier" />
        </el-form-item> -->
        <el-form-item label="省市区" prop="city">
          <AddressCascader ref="addressCascader" v-model="selectedOptions" @selectAddressDetail="selectAddressDetail" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="temp.address" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
        </el-form-item>
        <el-form-item label="是否默认">
          <el-radio-group v-model="temp.isDefault">
            <el-radio v-for="item in isDefaultJson" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <div class="footer">
      <Footer></Footer>
    </div>
  </div>
</template>

<script>
import { confirm, create } from "@/api/cart";
import { addressPageByQo, addressSetDefault, addressSaveOrUpdate, addressRemoveByIds } from '@/api/company'
import AddressCascader from '@/components/AddressCascader'
import Footer from "@/views/front/components/Footer";
import Header from "@/views/front/components/Header";
export default {
  data() {
    const validateCity = (rule, value, callback) => {
      if (!this.temp.districtId) {
        callback(new Error('请选择省市区'))
      } else {
        callback()
      }
    }
    return {
      addressList: [],
      addressId: '',
      confirmInfor: {},
      flag: false,
      temp: {
        id: 0,
        name: '',
        mobile: '',
        identifier: '',
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityName: '',
        districtId: '',
        districtName: '',
        address: '',
        isDefault: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑地址',
        create: '添加地址'
      },
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'change' }],
        mobile: [{ required: true, validator: this.$mobileValidator, trigger: 'blur' }],
        address: [{ required: true, message: '请输入', trigger: 'blur' }],
        city: [{ required: true, trigger: 'blur', validator: validateCity }]
      },
      multipleSelection: [],
      selectedOptions: [],
      isDefaultJson: [
        { label: '否', value: 0 },
        { label: '是', value: 1 },
      ],
      logicId: '1'
    };
  },
  created() {
    this.getAddressList()
    this.getConfirm()
  },
  destroyed() {
  },
  components: {
    AddressCascader,
    Footer,
    Header
  },
  computed: {
  },
  watch: {
  },
  methods: {
    // 订单信息
    getConfirm() {
      const cartIds = this.$route.query.cartIds
      const params = {
        cartIds
      }
      confirm(params).then((respanse) => {
        this.confirmInfor = respanse
      });
    },
    // 获取收货地址
    getAddressList() {
      addressPageByQo().then((respanse) => {
        const { list } = respanse
        this.addressList = list
        if (this.addressId) {
          return;
        }
        for (let i = 0; i < list.length; i++) {
          if (list[i].isDefault) {
            this.addressId = list[i].id
            return
          }
          this.addressId = list[0] ? list[0].id : ''
        }
      });
    },
    resetTemp() {
      this.temp = {
        id: 0,
        name: '',
        mobile: '',
        identifier: '',
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityName: '',
        districtId: '',
        districtName: '',
        address: '',
        isDefault: 0
      }
    },
    selectAddressDetail(value) {
      if (value) {
        this.$set(this.temp, `provinceId`, value.provinceId)
        this.$set(this.temp, `provinceName`, value.provinceName)
        this.$set(this.temp, `cityId`, value.cityId)
        this.$set(this.temp, `cityName`, value.cityName)
        this.$set(this.temp, `districtId`, value.districtId)
        this.$set(this.temp, `districtName`, value.districtName)
      } else {
        this.$set(this.temp, `provinceId`, '')
        this.$set(this.temp, `provinceName`, '')
        this.$set(this.temp, `cityId`, '')
        this.$set(this.temp, `cityName`, '')
        this.$set(this.temp, `districtId`, '')
        this.$set(this.temp, `districtName`, '')
      }
    },
    handleAdd() {
      this.resetTemp()
      this.selectedOptions = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      if (this.temp.districtId) {
        this.selectedOptions = [this.temp.provinceId.toString(), this.temp.cityId.toString(), this.temp.districtId.toString()]
      } else {
        this.selectedOptions = []
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    saveData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          delete this.temp.createTime
          addressSaveOrUpdate(this.temp, this.dialogStatus !== 'create').then(() => {
            this.getAddressList()
            this.dialogFormVisible = false
            // this.$notify({
            //   title: '成功',
            //   message: '保存成功',
            //   type: 'success',
            //   duration: 2000
            // })

            this.$message({
              message: '保存成功',
              type: 'success'
            });
          })
        }
      })
    },
    //创建订单
    handleCreate() {
      if (this.logicId == '1') {// 快递
        if (!this.addressId) {
          this.$message({
            message: '请选择收货地址！',
            type: 'warning'
          });
          return
        }
      } else { // 自提
        this.addressId = ''
      }
      
      this.flag = true
      const params = {
        addressId: this.addressId,
        cartIds: this.$route.query.cartIds,
        remark: this.confirmInfor.countDTOS[0].remark,
        logicId: this.logicId
      }
      create(params).then((respanse) => {
        // this.$notify.success({
        //   title: '温馨提示',
        //   message: '订单创建成功！'
        // });

        this.$message({
          message: '订单创建成功！',
          type: 'success'
        });

        // confirm-pay
        // this.$router.go(-1);
        this.$router.push({ path: '/confirm-pay', query: { id: respanse.orderIds, amount: this.confirmInfor.payAmount, orderNb: respanse.orderIdentifier, isPay: 1 } })
        this.flag = false
      }).catch(err => {
        this.flag = false
      })
    }
  },
};
</script>
<style>
.address .el-radio__input.is-checked .el-radio__inner {
  border-color: #952825;
  background: #952825;
}
.address .el-radio__input + .el-radio__label {
  white-space: pre-wrap;
  color: #333;
}
.address .el-radio__input.is-checked + .el-radio__label {
  white-space: pre-wrap;
  color: #333;
}
</style>
<style lang="scss" scoped>
.clearfix:after {
  content: "";
  display: block;
  clear: both;
}
.clearfix {
  zoom: 1;
}
.content {
  padding-top: 10px;
  margin: 0 auto;
  width: 1200px;
  .add {
    margin: 5px 0 0 154px;
    line-height: 40px;
    font-size: 14px;
    color: #952825;
    cursor: pointer;
  }
  .title {
    line-height: 60px;
    font-size: 16px;
    color: #333;
  }
  .item {
    padding: 0 26px;
    display: flex;
    line-height: 45px;
    box-sizing: border-box;
    .icon {
      margin: 8px 14px 0 0;
      width: 25px;
      height: 32px;
      visibility: hidden;
    }
    .titl {
      margin-right: 16px;
      font-size: 14px;
      color: #952825;
      visibility: hidden;
    }
    .con {
      flex: 1;
      padding: 13px 0;
      max-width: 960px;
      line-height: 20px;
      font-size: 14px;
      color: #333;
    }
    .btn {
      font-size: 14px;
      color: #333;
      cursor: pointer;
    }
    &.on {
      border: 1px solid #952825;
      background-color: #f6e1e0;
      .icon {
        visibility: visible;
      }
      .titl {
        visibility: visible;
      }
      .btn {
        color: #952825;
      }
    }
  }
  .order-infor {
    .title {
      border-bottom: 1px solid #952825;
    }
    .seller {
      .seller-name {
        padding: 20px 0;
        line-height: 20px;
        font-size: 14px;
        color: #333;
      }
      .product {
        display: flex;
        padding: 20px;
        background-color: #fff6f7;
        border: 1px solid #dedede;
        border-bottom: none;
        .icon {
          width: 82px;
          height: 82px;
          background-color: #fff;
        }
        .name {
          margin-left: 20px;
          width: 290px;
          line-height: 28px;
          font-size: 14px;
          color: #333;
        }
        .specifications {
          margin-left: 23px;
          width: 215px;
          line-height: 28px;
          font-size: 14px;
          color: #333;
        }
        .price {
          margin-left: 20px;
          width: 145px;
          line-height: 28px;
          font-size: 14px;
          font-weight: bold;
          color: #333;
          word-break: break-all;
        }
        .num {
          margin-left: 20px;
          width: 110px;
          line-height: 28px;
          font-size: 14px;
          font-weight: bold;
          color: #333;
          word-break: break-all;
        }
        .total-price {
          margin-left: 20px;
          flex: 1;
          line-height: 28px;
          font-size: 14px;
          font-weight: bold;
          color: #962924;
          word-break: break-all;
        }
      }
      .bottom-wrapper {
        display: flex;
        justify-content: space-between;
        padding: 20px 26px 22px;
        background-color: #fff6f7;
        border: 1px solid #dedede;
        .left {
          display: flex;
          justify-content: space-between;
          width: 788px;
          .titl {
            line-height: 22px;
            font-size: 14px;
            color: #333;
          }
          .msg {
            padding: 0 12px;
            width: 688px;
            height: 87px;
            box-sizing: border-box;
            border-color: #dedede;
            line-height: 22px;
            font-size: 14px;
            color: #333;
            resize: none;
            outline: none;
            background-color: #fff;
          }
        }
        .right {
          width: 283px;
          .text {
            display: flex;
            justify-content: space-between;
            line-height: 34px;
            font-size: 14px;
            color: #333;
            .c {
              color: #952825;
            }
            .m {
              font-size: 18px;
              font-weight: bold;
            }
          }
        }
      }
    }
    .total {
      margin-top: 19px;
      line-height: 46px;
      text-align: right;
      font-size: 14px;
      color: #333;
      .c {
        color: #952825;
      }
      .m {
        font-size: 32px;
        font-weight: bold;
      }
    }
    .buyer-wrapper {
      line-height: 20px;
      text-align: right;
      font-size: 14px;
      color: #333;
    }
    .submit-wrapper {
      display: flex;
      flex-direction: row-reverse;
      margin-top: 25px;
      .return {
        margin: 29px 40px 0 0;
        line-height: 30px;
        font-size: 14px;
        color: #952825;
        cursor: pointer;
      }
      .submit {
        width: 136px;
        height: 53px;
        line-height: 53px;
        text-align: center;
        font-size: 18px;
        color: #fff;
        background-color: #952825;
        cursor: pointer;
        border: none;
        outline: none;
        &[disabled] {
          background-color: #999;
        }
      }
    }
  }
}
</style>
